package com.mlamp.链表;

import java.util.Arrays;

public class 两数之和 {
    public static void main(String[] args) {
        int[] inputs = new int[]{2, 7, 11, 15};
        int target = 9;
        int[] result = towNumber(inputs, target);
        System.out.println(Arrays.toString(result));
        result = twoNumbers(inputs, target);
        System.out.println(Arrays.toString(result));

        result = towNumbers(inputs, target);
        System.out.println(Arrays.toString(result));
    }


    /**
     * 双指针两数之和
     *
     * @param inputs
     * @param target
     * @return
     */

    public static int[] twoNumberSum(int[] inputs, int target) {
        int left = 0, right = inputs.length - 1;
        while (left < right) {
            int sum = inputs[left] + inputs[right];
            if (sum < target) left++;
            else if (sum > target) right--;
            else return new int[]{left, right};
        }
        return new int[]{-1, -1};
    }

    private static int[] twoNumbers2(int[] inputs, int target) {
        int left = 0, right = inputs.length - 1;
        while (left < right) {
            int sum = inputs[left] + inputs[right];
            if (sum == target) return new int[]{left, right};
            if (sum > target) right--;
            else left++;
        }
        return new int[]{-1, -1};
    }

    private static int[] twoNumbers(int[] inputs, int target) {
        int left = 0, right = inputs.length - 1;
        while (left < right) {
            int sum = inputs[left] + inputs[right];
            if (sum == target) return new int[]{left, right};
            if (sum > target) {
                right--;
            } else {
                left++;
            }
        }
        return new int[]{-1, -1};
    }


    public static int[] twoNumbersA(int[] inputs, int target) {
        int left = 0, right = inputs.length - 1;
        while (left < right) {
            int sum = inputs[left] + inputs[right];
            if (sum == target) return new int[]{left, right};
            else if (sum < target) left++;
            else right--;
        }
        return new int[]{-1, -1};
    }


    private static int[] towNumbers(int[] inputs, int target) {
        int left = 0, right = inputs.length - 1;
        while (left < right) {
            int tmp = inputs[left] + inputs[right];
            if (target == tmp) return new int[]{left, right};
            else if (tmp > target) right = right - 1;
            else left = left + 1;
        }
        return new int[]{-1, -1};
    }


    private static int[] towNumber(int[] inputs, int target) {
        int left = 0, right = inputs.length - 1;
        while (left < right) {
            int sum = inputs[left] + inputs[right];
            if (sum == target) return new int[]{left, right};
            if (sum < target) {
                left++;
            } else {
                right--;
            }
        }
        return new int[]{-1, -1};
    }
}
